<template>
  <card>
    <Divider orientation="left">
      查看详情
    </Divider>
    <el-row type="flex" justify="space-around" align="middle">
      <el-col :span="6">
        <p>会议室：{{ info.room }}</p>
        <p>会议发起人：{{ info.sponsorName }}</p>
        <p>会议开始时间：{{ info.date }}</p>
        <p>会议主题：{{ info.theme }}</p>
        <p>会议成员：</p>
      </el-col>
      <el-col :span="6">
        <p>会议编号：{{ info.id }}</p>
        <p>会议预期人数：{{ info.expectsize }}</p>
        <p>会议时长：{{ info.timeSize }}</p>
        <p>会议是否需要签到：{{ info.attendance ? '是' : '否' }}</p>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center" class="tableRow">
      <el-col :span="20">
        <el-table v-loading="loading" element-loading-background="rgb(247, 246, 246, 0.9)" :data="member" border highlight-current-row>
          <el-table-column label="成员编号" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.uid }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成员姓名" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.userDetail.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号码" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.userDetail.tel == null ? '无' : scope.row.userDetail.tel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="签到时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.signtime == null ? '无' : (scope.row.signtime | parseTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="删除成员" align="center">
            <template slot-scope="scope">
              <el-button type="danger" @click="handleDelete(scope.$index,scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
          <template slot="append">
            <el-button type="text" icon="el-icon-plus" @click="handleInvite">
              邀请其他成员
            </el-button>
          </template>
        </el-table>
        <invite-dialog :visible.sync="dialogVisible" :meeting-id.sync="id" :code.sync="code" />
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="18">
        <p style="font-size: 20px;text-align: left;">
          <img src="../../assets/icons/文件.png" alt="file" style="height: 1em;">
          相关文件：
        </p>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="18" class="fileList">
        <div v-for="item in uploadList" :key="item.size" v-loading="fileLoading" class="demo-upload-list" :title="item.name">
          <template>
            <img :src="item.url" :alt="item.name">
            <p class="alt">
              {{ item.alt ? item.alt : item.name }}
            </p>
            <div class="demo-upload-list-cover">
              <Icon type="ios-cloud-download-outline" @click.native="handleDownload(item)" />
              <Icon type="ios-trash-outline" @click.native="handleRemove(item)" />
            </div>
          </template>
        </div>

        <Upload
          ref="upload"
          :show-upload-list="false"
          :default-file-list="defaultList"
          :on-success="handleSuccess"
          :before-upload="handleBeforeUpload"
          multiple
          type="drag"
          action="/api/upload"
          :headers="{ Authorization: token }"
          style="display: inline-block;width:100px;"
        >
          <div style="width: 100px;height:100px;line-height: 100px;">
            <Icon type="ios-add" size="70" />
          </div>
        </Upload>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="18" style="position: relative;">
        <p style="font-size: 20px;text-align: left;">
          <img src="../../assets/icons/公告.png" alt="file" style="height: 1em;">
          发布公告&nbsp;/
          <el-popover
            placement="right-end"
            width="500"
            trigger="click"
            @hide="activeName = ''"
          >
            <el-collapse v-model="activeName" accordion>
              <el-collapse-item v-for="(item, index) in notice" :key="item.id" :title="item.title" :name="index">
                <div>{{ item.content }}</div>
              </el-collapse-item>
            </el-collapse>
            <el-button slot="reference" type="text" style="font-size: 20px;" @click="findNotice">
              已发布的
            </el-button>
          </el-popover>
        </p>
        <div>
          <label style="float: left;display: block;">
            标题：
          </label>
          <el-input v-model="notice.title" placeholder="" style="margin-left: 5em;display: block;width: auto;" />
        </div>
        <div style="margin-top: 1em;">
          <label style="float: left;display: block;">
            内容：
          </label>
          <el-input v-model="notice.content" type="textarea" :autosize="{ minRows: 6, maxRows: 8 }" placeholder="" style="margin-left: 5em;display: block;width: auto;" />
          <el-button type="primary" class="publish" @click="handlePublish">
            发布
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="50" type="flex" justify="center" style="margin-top: 2em;">
      <el-col :span="6">
        <el-button type="danger" @click="handleCancel">
          取消本次会议
        </el-button>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="handleReturn">
          返回会议列表
        </el-button>
      </el-col>
    </el-row>
  </card>
</template>

<script>
import Card from '@/components/Card'
import InviteDialog from './components/InviteDialog'
import { Divider, Upload, Icon } from 'iview'
import { parseTime } from '@/utils'
import { findMeetingById, getInvitationCode, updateMeeting, cancelMeeting } from '@/api/meeting'
import { findMeetingMember, deleteMeetingMember } from '@/api/meetingMember'
import { publishNotice, findNoticeByMeeting } from '@/api/notice'

export default {
  components: { Card, Divider, Upload, Icon, InviteDialog },
  filters: {
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 5) {
        return value.substring(0, 5) + '...'
      }
      return value
    },
    parseTime(time) {
      const date = new Date(time)
      return parseTime(date, '{y}-{m}-{d} {h}:{i}')
    }
  },
  data() {
    return {
      id: this.$route.params.id * 1,
      info: {},
      member: [],
      loading: true,
      fileLoading: false,
      dialogVisible: false,
      user: this.$store.state.user.id,
      token: this.$store.state.user.token,
      defaultList: [],
      uploadList: [],
      activeName: '',
      notice: {
        titie: '',
        content: ''
      },
      url: location.origin + '/#',
      code: '',
      fileList: []
    }
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.getMember()
      }
    }
  },
  created() {
    this.getInfo()
    this.getMember()
  },
  methods: {
    async getInfo() {
      this.fileLoading = true
      const res = await findMeetingById(this.id)
      this.fileList = []
      this.defaultList = []
      this.uploadList = []
      this.info = res.data.data
      if (!this.info.invitationcode) {
        this.handleCreate()
      }
      this.code = `${this.url}/joinMeeting/${this.info.invitationcode}`
      if (this.info.attachment) {
        Object.assign(this.fileList, this.info.attachment.split(','))
        this.fileList.forEach(f => {
          const lastIndex = f.lastIndexOf('/')
          const name = f.substring(lastIndex + 1)
          let alt
          if (name.length > 7) {
            alt = this.handleExceed(name)
          }
          const suffix = this.getSuffix(name)
          const url = this.changeIcon(suffix)
          this.defaultList.push({ name, url, alt, f })
        })
        Object.assign(this.uploadList, this.defaultList)
      }
      this.filterData()
      setTimeout(() => {
        this.fileLoading = false
      }, 500)
    },
    async getMember() {
      this.loading = true
      const res = await findMeetingMember(this.id)
      this.member = res.data.data
      setTimeout(() => {
        this.loading = false
      }, 500)
    },
    filterData() {
      const data = this.info
      // console.log(`data:`, data)
      // this.transformState(data)
      data.date = parseTime(data.starttime, '{h}:{i}')
      data.timeSize = `${(data.endtime - data.starttime) / 60}分钟`
      data.sponsorName = `我`
    },
    async handleDelete(index, row) {
      const members = [row.id]
      const res = await deleteMeetingMember(this.id, members)
      if (res.data.code === 0) {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      }
    },
    async handleCreate() {
      const res = await getInvitationCode(this.id)
      this.info.invitationcode = res.data.data.invitationcode
    },
    handleInvite() {
      this.dialogVisible = true
    },
    getSuffix(name) {
      return name.split('.')[1]
    },
    handleExceed(name) {
      name = `${name.substring(0, 5)}...`
      return name
    },
    handleDownload(file) {
      // console.log(file)
      const path = file.f.substring(0, file.f.lastIndexOf('/'))
      window.open(`/api/download?path=${path}&name=${file.name}`)
    },
    handleRemove(file) {
      // console.log(file)
      // this.uploadList.splice(this.uploadList.indexOf(file), 1)
      // this.fileList.splice(this.fileList.indexOf(file), 1)
      const atts = this.fileList.filter(f => {
        return f !== file.f
      })
      let attachment = null
      if (atts.length) {
        attachment = atts[0]
        for (let i = 1; i < atts.length; i++) {
          attachment = `${attachment},${atts[i]}`
        }
        // console.log(attachment)
      }
      const meeting = {
        id: this.id,
        attachment,
        theme: this.info.theme,
        attendance: this.info.attendance,
        invite: this.info.invite
      }
      // console.log(meeting)
      updateMeeting(meeting).then(res => {
        if (!res.data.code) {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        }
        this.getInfo()
      })
    },
    handleSuccess(res, file, fileList) {
      const { path, name } = res.data
      let attachment
      if (this.info.attachment) {
        attachment = `${this.info.attachment},${path}${name}`
      } else {
        attachment = `${path}${name}`
      }
      const meeting = {
        id: this.id,
        attachment,
        theme: this.info.theme,
        attendance: this.info.attendance,
        invite: this.info.invite
      }
      console.log(meeting)
      let alt
      if (name.length > 7) {
        alt = this.handleExceed(name)
      }
      const suffix = this.getSuffix(name)
      const url = this.changeIcon(suffix)
      this.uploadList.push({ name, url, alt })
      updateMeeting(meeting).then(res => {
        if (!res.data.code) {
          this.$notify({
            title: '成功',
            message: '上传成功',
            type: 'success',
            duration: 2000
          })
        }
        this.getInfo()
      })
    },
    changeIcon(suffix) {
      switch (suffix) {
        case 'pdf':
          return require('../../assets/icons/pdf.png')
        case 'pptx':
        case 'ppt':
          return require('../../assets/icons/ppt.png')
        case 'zip':
        case 'rar':
          return require('../../assets/icons/rar.png')
        case 'xls':
        case 'xlsx':
          return require('../../assets/icons/xls.png')
        case 'doc':
        case 'docx':
          return require('../../assets/icons/文档.png')
        default:
          return require('../../assets/icons/空白.png')
      }
    },
    handleBeforeUpload() {
      this.fileLoading = true
    },
    async findNotice() {
      const res = await findNoticeByMeeting(this.id)
      this.notice = res.data.data
    },
    async handlePublish() {
      const { title, content } = this.notice
      const res = await publishNotice(this.id, title, content)
      if (res.data.code === 0) {
        this.$notify({
          title: '成功',
          message: '发布成功',
          type: 'success',
          duration: 2000
        })
        this.notice.title = ''
        this.notice.content = ''
      } else {
        this.$notify({
          title: '失败',
          message: '发布失败',
          type: 'error',
          duration: 2000
        })
      }
    },
    handleCancel() {
      this.$confirm('此操作将取消当前会议, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelMeeting(this.id).then(res => {
          if (!res.data.code) {
            this.$notify({
              title: '成功',
              message: '会议取消成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    handleReturn() {
      this.$router.push({ path: '/myMeeting' })
    }
  }
}
</script>

<style scoped>
.ivu-divider {
  font-size: 24px;
  font-weight: 400;
  margin-top: 1em;
  padding-left: 2em;
  padding-right: 2em;
}

.ivu-divider:before,
.ivu-divider:after {
  border-top-color: #F3AC8E;
}

.el-col {
  display: flex;
  flex-direction: column;
  justify-content: center;
  font-size: 20px;
  text-align: left;
}

.el-col p {
  margin-top: 10px;
  margin-bottom: 10px;
}

.tableRow {
  margin-top: 1em;
  /* height: 50%; */
}

.el-table::before,
.el-table--border::after {
  background-color: #707070;
}

.el-table--border >>> th,
.el-table--border >>> td {
  border-right: none;
}

.el-table {
  /* border: 1px solid #707070;
  border-bottom: none; */
  border-color: #707070;
  background-color: inherit;
  width: 90%;
  margin: 0 auto;
}

.el-table >>> th {
  background-color: #F7F6F6;
}

.el-table >>> th.is-leaf,
.el-table >>> td {
  border-color: #707070;
}

.el-table >>> .el-table__append-wrapper {
  display: flex;
  justify-content: center;
}

div >>> .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 102px;
}

div >>> .el-upload-list__item {
  width: 100px;
  height: 100px;
}

.demo-upload-list{
  display: inline-block;
  width: 132px;
  height: 132px;
  text-align: center;
  line-height: 0;
  /* border: 1px solid transparent; */
  border-radius: 4px;
  overflow: hidden;
  /* background: #fff; */
  position: relative;
  /* box-shadow: 0 1px 1px rgba(0,0,0,.2); */
  margin-right: 4px;
}

.demo-upload-list .alt {
  margin-top: 1em;
}

.demo-upload-list img{
  width: 100px;
  height: 100px;
}
.demo-upload-list-cover{
  display: none;
  position: absolute;
  line-height: 100px;
  height: 100px;
  width: 100px;
  top: 0;
  bottom: 0;
  left: 16px;
  right: 0;
  background: rgba(0,0,0,.6);
}
.demo-upload-list:hover .demo-upload-list-cover{
  display: block;
}
.demo-upload-list-cover i{
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}

.ivu-upload >>> .ivu-upload-drag:hover {
  border-color: #EF8558;
}

.fileList {
  flex-direction: row;
  justify-content: flex-start;
}

.publish {
  position: absolute;
  right: 1.5em;
  bottom: .5em;
}

.el-input >>> .el-input__inner,
.el-textarea >>> .el-textarea__inner {
  color: #000;
  font-size: 20px;
  border-color: #D1D1D1;
}

</style>
